<script setup>
name: 'params'
import { ref, onMounted, computed, nextTick } from 'vue'
import { getCategoriesListAPI, getparameterListAPI, addparameterAPI, editparameterAPI, delparameterAPI } from '@/api/productAPI'
import { ElMessage } from 'element-plus';


const props = {
    value: 'cat_id',
    label: 'cat_name',
    expandTrigger: 'hover',
}

const categorieslist = ref([])
const actionCascader = ref([])
const total = ref(0)
const getCategoriesList = async () => {
    const { data: res } = await getCategoriesListAPI()
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    categorieslist.value = res.data
    total.value = res.data.total
}
const manyOrOnlyList = ref([])
const roleId = ref(null)
const activeName = ref('many')

const getparameterList = async (roleId, activeName) => {
    const { data: res } = await getparameterListAPI(roleId, activeName)
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : item.attr_vals
        item.inputVisible = false
        item.inputValue = ''
    });
    manyOrOnlyList.value = res.data
}
const changeActionCascader = (val) => {
    roleId.value = null
    manyOrOnlyList.value = []
    if (val) {
        getparameterList(val[val.length - 1], activeName.value)
        roleId.value = val[val.length - 1]
    }
}

const tabChange = () => {
    if (!roleId.value) return;
    getparameterList(roleId.value, activeName.value)
}

// 表单验证
const rules = {
    attr_name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' }
    ],
}

// 添加参数

// 判断添加参数按钮是否禁用
const isButton = computed(() => {
    return actionCascader.value.length > 0 ? false : true
})

const addDialogVisible = ref(false)
// 判断对话框参数名称
const isTitle = computed(() => {
    return activeName.value === 'many' ? '动态参数' : '静态属性'
})
const addForm = ref({
    // 参数名称
    attr_name: ''
})
const addFormRef = ref(null)
// 添加对话框关闭事件
const addHandleClose = () => {
    addFormRef.value.resetFields()
}
// 添加参数按钮
const addParams = async () => {
    addForm.value.attr_sel = activeName.value
    addForm.value.attr_vals = ''
    const { data: res } = await addparameterAPI(roleId.value, addForm.value)
    if (res.meta.status !== 201) return ElMessage.error(res.meta.msg)
    ElMessage.success(res.meta.msg)
    addDialogVisible.value = false
    getparameterList(roleId.value, activeName.value)
}

// 添加参数标签
const editForm = ref({
    attr_id: 0,
    attr_name: '',
    attr_vals: ''
})
// 显示添加参数信息input框
const InputRef = ref(null)
const showInput = (params) => {
    params.inputVisible = true
    nextTick(() => {
        InputRef.value.focus()
    })
}

const tagHandleClose = (row, index) => {
    row.attr_vals.splice(index, 1)
    editparameter(roleId.value, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: activeName.value,
        attr_vals: row.attr_vals.join(' ')
    })
}

const editparameter = async (id, attrId, data) => {
    const { data: res } = await editparameterAPI(id, attrId, data)
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    ElMessage.success(res.meta.msg)
}

const handleInputConfirm = async (params) => {
    if (params.inputValue.trim().length === 0) {
        params.inputValue = ''
        params.inputVisible = false
        return
    }
    editForm.value.attr_name = params.attr_name
    editForm.value.attr_sel = activeName.value
    params.attr_vals.push(params.inputValue.trim())
    params.inputValue = ''
    editForm.value.attr_vals = params.attr_vals.join(' ')
    editparameter(roleId.value, params.attr_id, editForm.value)
    params.inputVisible = false
    editForm.value = {
        attr_id: 0,
        attr_name: '',
        attr_vals: ''
    }
}
// 修改参数
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editHandleClose = () => {
    editFormRef.value.resetFields()
}
// 显示修改参数对话框
const showEditDialog = (row) => {
    editForm.value.attr_id = row.attr_id
    editForm.value.attr_name = row.attr_name
    editForm.value.attr_vals = row.attr_vals
    editDialogVisible.value = true
}
// 点击修改按钮
const editParams = () => {
    editFormRef.value.validate(async (valid) => {
        if (valid) {
            console.log(editForm.value);
            await editparameter(roleId.value, editForm.value.attr_id, {
                attr_name: editForm.value.attr_name,
                attr_sel: activeName.value,
                attr_vals: editForm.value.attr_vals.join(' ')
            })
            editDialogVisible.value = false
            await getparameterList(roleId.value, activeName.value)
            editForm.value = {
                attr_id: 0,
                attr_name: '',
                attr_vals: ''
            }
        }
    })
}

// 点击修改按钮
const delParams = async (row) => {
    const confirmResult = await ElMessageBox.confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).catch(err => err)
    if (confirmResult === 'confirm') {
        const { data: res } = await delparameterAPI(roleId.value, row.attr_id)
        if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        getparameterList(roleId.value, activeName.value)
    } else {
        ElMessage.info('已取消删除')
    }
}

onMounted(() => {
    getCategoriesList()
})

</script>

<template>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <el-alert title="注意：只允许为第三级设置相关参数！" type="warning" show-icon :closable="false" />
        <div class="cascader">
            <p>请选择商品分类：</p>
            <el-cascader v-model="actionCascader" :options="categorieslist" :props="props" clearable
                @change="changeActionCascader" />
        </div>

        <el-tabs v-model="activeName" @tab-change="tabChange">
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" @click="addDialogVisible = true" :disabled="isButton">添加参数</el-button>
                <el-table :data="manyOrOnlyList" style="width: 100%" stripe border row-key="cat_id">
                    <el-table-column type="expand">
                        <template #default="props">
                            <el-tag v-for="(tag, index) in props.row.attr_vals" :key="tag" closable disable-transitions
                                size="large" @close="tagHandleClose(props.row, index)">
                                {{ tag }}
                            </el-tag>
                            <el-input v-if="props.row.inputVisible" ref="InputRef" v-model="props.row.inputValue"
                                class="tag_input" size="small" @keyup.enter="handleInputConfirm(props.row)"
                                @blur="handleInputConfirm(props.row)" />
                            <el-button v-else size="small" @click="showInput(props.row)">
                                + New Tag
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column prop="attr_name" label="参数名称" />
                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-button type="primary" icon="Edit" size="small"
                                @click="showEditDialog(scope.row)">编辑</el-button>
                            <el-button type="danger" icon="Delete" size="small" @click="delParams(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" @click="addDialogVisible = true" :disabled="isButton">添加参数</el-button>
                <el-table :data="manyOrOnlyList" style="width: 100%" stripe border row-key="cat_id">
                    <el-table-column type="expand">
                        <template #default="props">
                            <el-tag v-for="(tag, index) in props.row.attr_vals" :key="tag" closable disable-transitions
                                size="large" @close="tagHandleClose(props.row, index)">
                                {{ tag }}
                            </el-tag>
                            <el-input v-if="props.row.inputVisible" ref="InputRef" v-model="props.row.inputValue"
                                class="tag_input" size="small" @keyup.enter="handleInputConfirm(props.row)"
                                @blur="handleInputConfirm(props.row)" />
                            <el-button v-else size="small" @click="showInput(props.row)">
                                + New Tag
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column prop="attr_name" label="参数名称" />
                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-button type="primary" icon="Edit" size="small"
                                @click="showEditDialog(scope.row)">编辑</el-button>
                            <el-button type="danger" icon="Delete" size="small" @click="delParams(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog v-model="addDialogVisible" :title="`添加${isTitle}`" width="50%" @closed="addHandleClose">
        <el-form :model="addForm" ref="addFormRef" :rules="rules">
            <el-form-item :label="isTitle" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addParams">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog v-model="editDialogVisible" :title="`修改${isTitle}`" width="50%" @closed="editHandleClose">
        <el-form :model="editForm" ref="editFormRef" :rules="rules">
            <el-form-item :label="isTitle" prop="attr_name">
                <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="editParams">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.cascader {
    display: flex;
    margin: 10px;
}

.el-tag {
    margin: 10px;
}

.tag_input {
    width: 90px;
    margin-left: 10px;
    vertical-align: baseline;
}
</style>